<template>
  <div class="">
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div>
          <el-form-item>
            <el-input v-model="key" clearable placeholder="用户名、姓名、手机号" style="width: 200px;" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="uid" clearable placeholder="用户ID" style="width: 100px;" />
          </el-form-item>
          <el-form-item>
            <label>币种：</label>
            <el-select v-model="coinid" placeholder="请选择">
              <el-option label="全部" :value="-1" />
              <el-option v-for="item in coinList" :disabled="item.coinid == 3" :label="item.coinname"
                :value="item.coinid" />
            </el-select>
          </el-form-item>
          <!--  <el-form-item>
            <el-date-picker v-model="dateTime" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="reset">重置</el-button>
          </el-form-item>
          <div />
        </div>
        <div>
          <el-form-item>
            <el-button type="primary" :loading="exportLoading" @click="doExport">导出Excel</el-button>
          </el-form-item>
        </div>
      </div>

    </el-form>
    <el-table v-loading="listLoading" :data="tableData" border style="width: 100%" @sort-change="onSortChange">
      <el-table-column prop="uid" label="用户ID" align="center" />
      <el-table-column prop="userName" label="用户名" align="center" />
      <el-table-column prop="trueName" label="姓名" align="center" />
      <el-table-column prop="coinid" label="币种" align="center">
        <template slot-scope="{row}">
          <span v-if="row.coinid == item.coinid" v-for="item in coinList">{{ item.coinname }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="balance" label="余额" align="center" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.balance }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="lockbalance" label="冻结金额" align="center" />
      <el-table-column label="操作" width="200px" align="center">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary"
            @click="$router.push({ name: 'BalanceRecord', query: { userid: row.uid, coinid: row.coinid } })">资金记录</el-button>
          <el-button size="mini" type="primary" @click="recharge(row)">充值</el-button>
          <!-- <el-button size="mini" type="danger" @click="onDelete(row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div v-if="totalCount > pageSize" class="block " style="padding-top: 20px;">
      <el-pagination background :current-page="PageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="totalCount" @size-change="idx => { pageSize = idx }"
        @current-change="idx => { PageIndex = idx }" />
    </div>

    <!-- 系统充值弹窗 -->
    <el-dialog title="系统充值" :visible="dialogVisible" width="600px" :modal-append-to-body="false" @close="handleClose">
      <el-form ref="form" :model="form" :rules="rulesModel" class="form" label-width="130px">
        <el-form-item label="币种">
          <!-- <el-input v-model.number="form.coinname" placeholder="请输入金额" /> -->
          <span v-if="form.coinid == item.coinid" v-for="item in coinList">{{ item.coinname }}</span>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="form.amount" type="number" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="AddBalance">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { userbalance, AddBalance, userbalanceExcel } from '../../../api/users.js'
import { getEnumList } from '@/utils/auth.js'
import { GetEnum, coinlist } from "@/api/ctrls.js";
export default {
  name: 'Name',
  data() {
    return {
      coinid: -1,
      uid: '',
      username: '',
      key: '', // 关键词
      sort: '',
      dateTime: ['', ''], // 时间查询


      listLoading: false,
      tableData: [],
      totalCount: 0,
      PageIndex: 1,
      pageSize: 20,
      listLoading: false,
      total: {},

      tradetyep: {},
      coinList: [], // 币种列表

      //  添加余额弹窗
      dialogVisible: false,
      form: {},
      rulesModel: {
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ]
      },

      exportLoading: false, // 导出loading
    }
  },
  computed: {},
  watch: {
    PageIndex(val) {
      this.getData()
    },
    pageSize(val) {
      this.getData()
    }
  },
  async mounted() {
    this.uid = this.$route.query.userid || ''
    this.coinid = this.$route.query.coinid || ''
    this.getData()
    this.GetEnum();
    this.GetCoin();
  },
  methods: {
    // 关闭前
    handleClose() {
      this.$refs.form.resetFields()
      this.$refs.form.clearValidate()
      this.setForm();
      this.dialogVisible = false;
    },
    setForm() {
      this.form = {
        uid: 0, // 用户id
        amount: 0, // 金额
        coinid: 0, // 币种id
        remark: '', // 备注
      }
    },
    // 系统充值
    recharge(item) {
      this.setForm();
      this.form.userid = item.uid;
      this.form.coinid = item.coinid;
      this.dialogVisible = true;
    },
    reset() {
      this.coinid = -1
      this.key = ''
      this.username = "";
      this.sort = 1;
      this.onSearch()
    },
    async onSearch() {
      this.PageIndex = 1
      this.getData()
    },
    // 排序监听
    onSortChange(column) {
      console.log('aas', column)
      if (column.order == 'ascending') {
        this.sort = '1';
      } else if (column.order == 'descending') {
        this.sort = '2';
      } else {
        this.sort = '';
      }
      this.onSearch();
    },
    /////////////////////// 导出报表  ///////////////////////
    // 导出报表
    async doExport() {
      this.exportLoading = true;
      const res = await userbalanceExcel({
        key: this.key,
        coinid: this.coinid,
        uid: this.uid,
        sort: this.sort,
      });
      this.exportLoading = false;
      if (res) {
        console.log('导出网络数据：：', res);
        // 文件名
        const fileName = "用户余额列表.xlsx";
        // 处理导出数据并下载
        this.handleExcel(res, fileName);
      }
    },
    /**转换数据类型  下载Excel报表 */
    handleExcel(data, fileName) {
      //转换数据类型
      const xlsx = "application/vnd.ms-excel;charset=utf-8";
      const blob = new Blob([data], { type: xlsx });
      console.log(blob);

      // 转换完成，创建一个a标签用于下载
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = URL.createObjectURL(blob);
      a.setAttribute("download", fileName);
      document.body.appendChild(a);
      a.click();
      a.remove();
    },
    /**系统充值 */
    async AddBalance() {
      const { success, msg } = await AddBalance(this.form)
      if (success) {
        this.onSearch();
        this.dialogVisible = false;
      }
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
    },
    async gettradetyep() {
      const res = await gettradetyep()
      res.forEach(item => {
        this.tradetyep[item.value] = item.key
      })
      console.log(res)
    },
    async getData(address) {
      this.listLoading = true
      const { list, pageIndex, totalCount, total } = await userbalance({
        key: this.key,
        coinid: this.coinid,
        uid: this.uid,
        sort: this.sort,
        PageIndex: this.PageIndex,
        PageSize: this.pageSize
      })
      this.total = total
      this.totalCount = totalCount
      this.tableData = list
      this.listLoading = false
    },
    // 获取枚举
    async GetEnum() {
      const res = await GetEnum();
    },
    // 获取币种
    async GetCoin() {
      const res = await coinlist();
      this.coinList = res;
    },
  }
}
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
  background: oldlace;
}
</style>
